﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Hrm.Core;
using Hrm.EntityFramework;
using Hrm.Services;
using Hrm.Web.Framework;
using Newtonsoft.Json;

namespace Hrm.Web.Areas.Permissions.Controllers
{
    [RoleAuthorize]
    public class ResourcesController : Controller
    {
        IApplicationService _applicationService;
        IResourceService _resourceService;
        IDictionaryService _dictionaryService;
        ICacheManager _cacheManager;

        public ResourcesController(IResourceService resourceService, IApplicationService applicationService, IDictionaryService dictionaryService, ICacheManager cacheManager)
        {
            this._applicationService = applicationService;
            this._resourceService = resourceService;
            this._dictionaryService = dictionaryService;
            this._cacheManager = cacheManager;
        }

        private void InitData()
        {
            List<SelectListItem> applicationSelectItems = new SelectList(_applicationService.GetAll(), "Id", "Name").ToList();
            applicationSelectItems.Insert(0, (new SelectListItem { Text = "请选择", Value = "" }));
            ViewBag.ApplicationId = applicationSelectItems;

            List<SelectListItem> resourceSelectItems = new SelectList(_resourceService.GetList(p => p.IsEnable != false), "Code", "Name").ToList();
            resourceSelectItems.Insert(0, (new SelectListItem { Text = "资源根", Value = Constant.ResourceParentCodeMenuRoot }));
            ViewBag.ParentCode = resourceSelectItems;

            List<SelectListItem> resourceTypeSelectItems = new SelectList(this._dictionaryService.GetDictionaryByType(Constant.DictionaryRourseType), "Code", "Name").ToList();
            resourceTypeSelectItems.Insert(0, (new SelectListItem { Text = "请选择", Value = "" }));
            ViewBag.Type = resourceTypeSelectItems;
        }

        public ActionResult Index()
        {
            InitData();
            return View();
        }

        public JsonResult PageResources(PageRequest<ResourceDto> request)
        {
            var result = this._resourceService.GetPageList(request);
            return Json(result);
        }

        public ActionResult Create()
        {
            InitData();
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Resource resource, int applicationId)
        {
            if (ModelState.IsValid)
            {
                var app = _applicationService.GetById(applicationId);
                resource.Application = app;
                _resourceService.Insert(resource);
                this._cacheManager.Clear();
                return RedirectToAction("Index");
            }

            return View(resource);
        }

        public ActionResult Details(int id)
        {
            if (id == 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Resource resource = this._resourceService.GetById(id);
            if (resource == null)
            {
                return HttpNotFound();
            }
            InitData();
            return View(resource);
        }

        public ActionResult Edit(int id)
        {
            if (id == 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Resource resource = this._resourceService.GetById(id);
            if (resource == null)
            {
                return HttpNotFound();
            }
            InitData();
            return View(resource);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Resource resource)
        {
            if (ModelState.IsValid)
            {
                var model = this._resourceService.GetById(resource.Id);
                model.Name = resource.Name;
                if (TryUpdateModel(model, "", new string[] { "Id", "Code", "Name", "Type", "ParentCode", "QQ", "Order", "Url", "GlyphiconsClass", "Description" }))
                {
                    if (model.Application.Id != resource.Application.Id)
                    {
                        var temp = this._applicationService.GetById(resource.Application.Id);
                        model.Application = temp;
                    }
                    _resourceService.Update(model);
                }
                return RedirectToAction("Index");
            }
            return View();
        }

        [HttpPost]
        public JsonResult Delete(int id = 0)
        {
            ResponseModel result = new ResponseModel();
            if (id == 0)
            {
                result.SetFailed("删除失败，参数不能为空！");
                return Json(result);
            }
            Resource resource = this._resourceService.GetById(id);
            if (resource == null)
            {
                result.SetFailed("删除失败，查询没有改数据！");
                return Json(result);
            }
            this._resourceService.UpdateDisabled(resource);
            return Json(result);
        }

        public ActionResult EditPermission(int id = 0)
        {
            var model = this._resourceService.GetById(id);
            var permissionIds = model.ResourceAndPermissions != null ? model.ResourceAndPermissions.Select(p => p.Permission.Id) : new List<int>();
            ViewBag.PermissionIds = JsonConvert.SerializeObject(permissionIds);
            ViewBag.ResourceId = id;
            return View();
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult EditPermissionSubmit(EditPermissionDto request)
        {
            var result = this._resourceService.EditPermissionSubmit(request);
            return Json(result);
        }
    }
}
